# _*_ coding: utf-8 _*_
# .@FileName:connect_widget
# .@Data....:2025-01-29 : 00 : 37
# .@Aurhor..:LiuJingYu
"""
launch:
   import maya.cmds as cmds
   FileName.main() 
"""
from __future__ import unicode_literals, print_function

from enum import IntEnum
from typing import List, Optional
import config
from PySide2.QtCore import Qt
from PySide2.QtWidgets import *

import maya.cmds as mc

import attr_regex_match_dialog
# class FuncSelectWidget(QWidget):
#     Connect, DisConnect = range(2)
#     ConnectText = "建立连接"
#     DisConnectText = "断开连接"
#
#     def __init__(self, parent=None):
#         super(FuncSelectWidget, self).__init__(parent)
#         self.main_layout = QHBoxLayout(self)
#
#         self.f_com = QComboBox(self)
#
#         self.f_com.addItem(self.ConnectText)
#         self.f_com.addItem(self.DisConnectText)
#
#         self.main_layout.addWidget(QLabel("功能"))
#         self.main_layout.addWidget(self.f_com)
#         self.main_layout.addStretch(0)
#
#     def func(self):
#         if self.f_com.currentText() == self.ConnectText:
#             return self.Connect
#         else:
#             return self.Disconnect
#
# class MatchWidget(QWidget):
#     def __init__(self, parent=None):
#         super(MatchWidget, self).__init__(parent)
#         self.main_layout = QHBoxLayout()
#         self.name_text = QTextEdit()
#         self.r_layout = QVBoxLayout()
#         self.regex_match_bn = QPushButton("通过正则表达式匹配")
#
#         self.r_layout.addWidget(self.regex_match_bn)
#         self.r_layout.addStretch(0)
#
#         self.main_layout.addWidget(self.name_text)
#         self.main_layout.addLayout(self.r_layout)
#
#     def names(self):
#         return list(self.name_text.toPlainText().splitlines())
#
#
#
# class ConnetQWidgets(QWidget):
#     def __init__(self, parent=None):
#         super(ConnetQWidgets, self).__init__(parent)
#         self.main_layout = QVBoxLayout(self)
#
#         self.func_sel_widget = FuncSelectWidget(self)
#
#         self.match_out_attrs_widget = MatchWidget(self)
#         self.match_in_attrs_widget = MatchWidget(self)
#
#
#         self.main_layout.addWidget(self.func_sel_widget)
#         self.main_layout.addWidget(QLabel("输出属性： "))
#         self.main_layout.addWidget(self.match_out_attrs_widget)
#         self.main_layout.addWidget(QLabel("输入属性： "))
#         self.main_layout.addWidget(self.match_in_attrs_widget)

# 定义一个功能选择的窗口部件类，继承自 QWidget
class FuncOperation(IntEnum):
    """功能操作类型枚举 (兼容Python3.7)

    Attributes:
        CONNECT: 建立连接操作，对应整数值0
        DISCONNECT: 断开连接操作，对应整数值1
    """
    CONNECT = 0
    DISCONNECT = 1


class FuncSelectWidget(QWidget):
    """功能选择组件 (兼容Python3.7)

    提供连接/断开连接操作的选择功能，包含下拉选择框

    Attributes:
        TEXTS: 界面显示文本配置，元组格式（操作类型，显示文本）
        combo_box: 功能选择下拉框组件
    """

    # 界面文本常量配置（操作类型，显示文本）
    TEXTS = (
        (FuncOperation.CONNECT, "建立连接"),
        (FuncOperation.DISCONNECT, "断开连接"),
    )

    def __init__(self, parent=None):
        """初始化功能选择组件"""
        super().__init__(parent)

        # 主布局使用水平布局
        self.main_layout = QHBoxLayout(self)
        self.main_layout.setContentsMargins(0, 0, 0, 0)  # 去除边距

        # 初始化下拉选择框
        self.combo_box = QComboBox()
        # 使用列表推导式兼容Python3.7的语法
        self.combo_box.addItems([text for _, text in self.TEXTS])

        # 添加组件到布局
        self.main_layout.addWidget(QLabel("功能"))
        self.main_layout.addWidget(self.combo_box)
        self.main_layout.addStretch()  # 添加伸缩空间

    def selected_func(self) -> FuncOperation:
        """获取当前选择的功能

        Returns:
            FuncOperation: 当前选中的操作类型枚举值
        """
        return FuncOperation(self.combo_box.currentIndex())


class MatchWidget(QWidget):
    """属性匹配组件 (兼容Python3.7)

    用于输入和匹配属性名称，包含文本编辑框和正则匹配按钮

    Attributes:
        text_edit: 文本输入框组件
        btn_regex: 正则匹配按钮组件
    """

    def __init__(self, parent=None):
        """初始化属性匹配组件"""
        super().__init__(parent)

        # 主布局使用水平布局
        self.main_layout = QHBoxLayout(self)
        # 初始化文本编辑框
        self.text_edit = QTextEdit()
        self.text_edit.setMinimumHeight(100)  # 设置最小高度

        # 右侧按钮布局
        self.right_layout = QVBoxLayout()
        self.btn_regex = QPushButton("正则匹配")
        self.btn_regex.clicked.connect(self._on_regex_clicked)  # 连接点击信号

        self.right_layout.addWidget(self.btn_regex)
        self.right_layout.addStretch()  # 添加伸缩空间

        # 将组件添加到布局
        self.main_layout.addWidget(self.text_edit)
        self.main_layout.addLayout(self.right_layout)

    def _on_regex_clicked(self):
        """处理正则匹配按钮点击事件"""
        try:
            # 假设attr_regex_match_dialog是已定义的对话框对象
            result = attr_regex_match_dialog.exec_()  # 执行正则匹配对话框
            if result:
                # 将匹配结果设置为文本内容（用换行符连接）
                self.text_edit.setPlainText("\n".join(result))
        except Exception as e:
            QMessageBox.critical(self, "错误", f"正则匹配失败: {str(e)}")

    def get_names(self) -> List[str]:
        """获取处理后的属性名称列表

        返回格式化的非空属性名称列表，自动去除前后空格并过滤空行

        Returns:
            List[str]: 处理后的属性名称列表
        """
        return [
            line.strip()
            for line in self.text_edit.toPlainText().splitlines()
            if line.strip()  # 过滤空行
        ]


class ConnectWidget(QWidget):
    """主连接功能组件 (兼容Python3.7)

    整合功能选择、属性匹配和执行操作功能

    Attributes:
        func_selector: 功能选择组件
        match_output: 输出属性匹配组件
        match_input: 输入属性匹配组件
        btn_execute: 执行功能按钮
    """

    def __init__(self, parent=None):
        """初始化连接功能组件"""
        super().__init__(parent)

        # 主布局使用垂直布局
        self.main_layout = QVBoxLayout(self)
        # 初始化子组件
        self.func_selector = FuncSelectWidget()
        self.match_output = MatchWidget()
        self.match_input = MatchWidget()
        self.btn_execute = QPushButton("执行功能")

        # 设置执行按钮样式
        self.btn_execute.setStyleSheet("background-color: #4CAF50; color: white;")
        self.btn_execute.clicked.connect(self._execute_operation)  # 连接点击信号

        # 添加组件到布局
        self.main_layout.addWidget(self.func_selector)
        self.main_layout.addWidget(self._create_group("输出属性", self.match_output))
        self.main_layout.addWidget(self._create_group("输入属性", self.match_input))
        self.main_layout.addWidget(self.btn_execute)

    def _create_group(self, title: str, widget: QWidget) -> QGroupBox:
        """创建带标题的分组框

        Args:
            title: 分组框标题
            widget: 需要放入分组框的组件

        Returns:
            QGroupBox: 配置好的分组框实例
        """
        group = QGroupBox(title)
        layout = QVBoxLayout()
        layout.addWidget(widget)
        group.setLayout(layout)
        return group

    def _execute_operation(self):
        """执行连接/断开连接操作的主逻辑"""
        try:
            # 获取输入输出属性列表
            outputs = self.match_output.get_names()
            inputs = self.match_input.get_names()

            # 验证属性数量匹配
            if len(outputs) != len(inputs):
                raise ValueError("输入输出属性数量必须一致")

            # 获取当前选择的操作类型
            operation = self.func_selector.selected_func()

            # 遍历属性对执行操作（假设mc是Maya命令模块）
            for out_attr, in_attr in zip(outputs, inputs):
                if operation == FuncOperation.CONNECT:
                    mc.connectAttr(out_attr, in_attr)  # 建立连接
                else:
                    # 断开前检查连接状态
                    if mc.isConnected(out_attr, in_attr):
                        mc.disconnectAttr(out_attr, in_attr)  # 断开连接

            QMessageBox.information(self, "成功", "操作执行成功！")

        except ValueError as e:
            QMessageBox.warning(self, "输入错误", str(e))  # 输入验证错误
        except RuntimeError as e:
            QMessageBox.critical(self, "Maya错误", f"Maya操作失败: {str(e)}")  # Maya命令错误
        except Exception as e:
            QMessageBox.critical(self, "未知错误", f"发生意外错误: {str(e)}")  # 其他未知错误


def create_connect_widget() -> ConnectWidget:
    """创建连接功能组件

    Returns:
        ConnectWidget: 初始化好的连接功能组件实例
    """
    return ConnectWidget()

def new():
    return ConnectWidget()
